package elitech.vietnam.weatherfashion.tabs.today;

import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.backgroundtask.PostLikeTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.custom.ExpandableHeightGridView;
import elitech.vietnam.weatherfashion.custom.LikeButton;
import elitech.vietnam.weatherfashion.custom.RecentPostAdapter;
import elitech.vietnam.weatherfashion.custom.dialogues.TimeOutDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.dto.ProductDTO;
import elitech.vietnam.weatherfashion.dto.StoreDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;
import elitech.vietnam.weatherfashion.ultilities.MyDialogHandler;

public class TodayDetailFragment extends AbstractFragment implements View.OnClickListener {

	private PostDTO post;
	private StoreDTO store;
	private List<ProductDTO> products;
	private TextView text_shopname, text_shopprofile, text_postname, text_postprice;
	private ImageView image_avatar, image_shoppost;
	private LikeButton button_like;
	private Button button_back;
	private LinearLayout layout_product;
	private RelativeLayout layout_post;
	private ExpandableHeightGridView layout_recentpost;
	private List<PostDTO> recent_posts;
	private RecentPostAdapter mRAdapter;

	public static TodayDetailFragment init(PostDTO data) {
		TodayDetailFragment tmp = new TodayDetailFragment();
		tmp.post = data;
		return tmp;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.tab_todaydetail, container, false);
		setupView(view);

		text_shopname = (TextView) view.findViewById(R.id.shopinfo_textview_username);
		text_shopprofile = (TextView) view.findViewById(R.id.shopinfo_textview_userprofile);
		button_back = (Button) view.findViewById(R.id.todaydetail_button_back);
		image_avatar = (ImageView) view.findViewById(R.id.shopinfo_image_useravatar);
		button_like = (LikeButton) view.findViewById(R.id.shopinfo_button_like);
		image_shoppost = (ImageView) view.findViewById(R.id.todaydetail_post_image);
		text_postname = (TextView) view.findViewById(R.id.todaydetail_post_textname);
		text_postprice = (TextView) view.findViewById(R.id.todaydetail_post_textprice);
		layout_post = (RelativeLayout) view.findViewById(R.id.todaydetail_layout_post);
		layout_product = (LinearLayout) view.findViewById(R.id.todaydetail_layout_product);
		layout_recentpost = (ExpandableHeightGridView) view.findViewById(R.id.grid_recent_post);

		if (!isAdded())
			return null;

		button_like.setUp(true);
		button_like.setOnClickListener(this);
		button_back.setOnClickListener(this);

		if (store == null)
			new GetStoreInfo().execute();
		else
			setStoreInfo();
		if (products == null || products.isEmpty())
			new GetPostProduct().execute();
		else
			initProduct();
		if (recent_posts == null || recent_posts.isEmpty())
			new GetRecentPost().execute();
		else
			initRecentPost();
		button_like.setData(post.getLikes(), post.isLiked());

		return view;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	private void setStoreInfo() {
		if (this.store == null)
			return;

		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// store.getStorePic(), image_avatar);
		UrlImageViewHelper.setUrlDrawable(image_avatar, Const.SERVER_IMAGE_THUMB_URL + store.getStorePic(), R.drawable.no_avatar);
		this.text_shopname.setText(this.store.getStoreName());
		this.text_shopprofile.setText(this.store.getStoreProfile());
		this.text_shopname.setOnClickListener(this);
		this.image_avatar.setOnClickListener(this);
	}

	private void initProduct() {
		/*
		 * USING LINEARLAYOUT
		 */
		try {
			((ScrollView) layout_main).fullScroll(ScrollView.FOCUS_UP);
		} catch (ClassCastException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
			return;
		}
		
		if (this.products.isEmpty()) {
			setPostInfo();
			layout_post.setVisibility(View.VISIBLE);
			layout_product.setVisibility(View.GONE);
			return;
		}

		layout_post.setVisibility(View.GONE);
		layout_product.setVisibility(View.VISIBLE);

		LayoutInflater inflater = LayoutInflater.from(getActivity());

		for (final ProductDTO dto : this.products) {
			View view = inflater.inflate(R.layout.layout_product1, null);
			ImageView image = (ImageView) view.findViewById(R.id.product_image);
			TextView name = (TextView) view.findViewById(R.id.product_text_name);
			TextView price = (TextView) view.findViewById(R.id.product_text_price);

			Utils.setTextUnderline(name);
			Utils.setTextUnderline(price);
			// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL
			// + dto.getImage(), image);
			UrlImageViewHelper.setUrlDrawable(image, Const.SERVER_IMAGE_URL + dto.getImage(), R.drawable.loading_time);
			name.setText(dto.getTitle());
			price.setText(dto.getPrice() + Utils.getPriceCode());

			name.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Utils.openLink(getActivity(), dto.getLink());
				}
			});
			price.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Utils.openLink(getActivity(), dto.getLink());
				}
			});
			image.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Utils.openLink(getActivity(), dto.getLink());
				}
			});
			layout_product.addView(view);
		}
	}

	private void setPostInfo() {
		UrlImageViewHelper.setUrlDrawable(image_shoppost, Const.SERVER_IMAGE_URL + post.getImage(), R.drawable.loading_time);
		text_postname.setText(post.getTitle());
		text_postprice.setText(post.getPrice() + Utils.getPriceCode());
		Utils.setTextUnderline(text_postname);
		Utils.setTextUnderline(text_postprice);
		text_postprice.setOnClickListener(this);
		text_postname.setOnClickListener(this);
		image_shoppost.setOnClickListener(this);
	}

	private void initRecentPost() {
		if (recent_posts == null || recent_posts.isEmpty() || getView() == null)
			return;
		layout_recentpost.setExpanded(true);
		recent_posts.removeAll(Collections.singleton(null));
		View view = getView().findViewById(R.id.layout_recentpost_root);
		if (view != null)
			view.setVisibility(View.VISIBLE);
		mRAdapter = new RecentPostAdapter(getActivity(), R.layout.layout_recent_post_item, recent_posts);
		mRAdapter.setOnItemClickListener(new RecentPostAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(PostDTO item) {
				layout_product.removeAllViews();
				post = item;
				new GetPostProduct().execute();
				new GetRecentPost().execute();
			}
		});
		layout_recentpost.setAdapter(mRAdapter);
	}
	
	@Override
	public void onClick(View v) {

		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {

		case R.id.shopinfo_button_like:
			button_like.setEnabled(false);
			if (user == null) {
				Utils.openLogin(getActivity());

			} else {
				String ms = getString(R.string.do_you_want_to_like_this_post_);

				if (post.isLiked())
					ms = getString(R.string.do_you_want_to_unlike_this_post_);

				new MyDialogHandler().confirm(getActivity(), getString(R.string.like_confirm), ms, getString(R.string.no), getString(R.string.yes), new Runnable() {
					@Override
					public void run() {
						new PostLikeTask(getActivity(), button_like, post, !post.isLiked()).execute();
					}
				}, null);
			}
			button_like.setEnabled(true);
			break;

		case R.id.shopinfo_textview_username:
			Utils.openLink(getActivity(), store.getStoreHome());
			break;

		case R.id.shopinfo_image_useravatar:
			Utils.openLink(getActivity(), store.getStoreHome());
			break;

		case R.id.todaydetail_post_textname:
			Utils.openLink(getActivity(), post.getLink());
			break;

		case R.id.todaydetail_post_textprice:
			Utils.openLink(getActivity(), post.getLink());
			break;

		case R.id.todaydetail_post_image:
			Utils.openLink(getActivity(), post.getLink());
			break;

		case R.id.todaydetail_button_back:
			getActivity().onBackPressed();
			break;

		default:
			break;
		}
	}

	/*
	 * GET DATA TASKS
	 */
	class GetStoreInfo extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				store = appService.getInfoStore(post.getStoreId());
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			setStoreInfo();
		}
	}

	class GetPostProduct extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				products = appService.getListProduct(post.getId());
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			onLoading(false);
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			initProduct();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!isAdded())
				return;
			onLoading(true);
		}
	}

	class GetRecentPost extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			Date date = new Date();
			try {
				int index = Utils.getDateDiff(date, post.getDateShow()) * -1;
				 recent_posts = appService.getThumbnailFashion(post.getStoreId(), index, Const.MAX_RECENT_ITEM * -1);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			initRecentPost();
		}
	}
}
